package com.tinem.platform.service.message.api;


import com.tinem.platform.module.pojo.co.RedisKeyEnum;
import com.tinem.platform.module.pojo.enums.message.MqttMessageType;
import com.tinem.platform.module.pojo.vo.error.SystemException;
import com.tinem.platform.module.pojo.vo.message.online.StatusReq;
import com.tinem.platform.module.pojo.vo.message.online.StatusRes;
import com.tinem.platform.module.starter.EmqxClient;
import com.tinem.platform.module.starter.sdk.MessageCode;
import com.tinem.platform.module.starter.web.context.GatewayContext;
import com.tinem.platform.service.message.config.ClientConfiguration;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@Controller
@Api(value = "online")
@RequestMapping("online")
public class OnlineApi {

    @Value("${spring.profiles.active}")
    protected String active;

    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    EmqxClient emqxClient;
    @Resource
    ClientConfiguration clientConfiguration;

    @ResponseBody
    @PostMapping("/status.api")
    @ApiOperation(value = "是否在线状态判断", httpMethod = "POST", notes = "暂无")
    public StatusRes status(@RequestBody StatusReq statusReq, HttpServletRequest request){
        String clientId = GatewayContext.getClient();
        ClientConfiguration.Config config = clientConfiguration.getConfig().get(clientId);
        if(config == null){
            log.error("client config not find:{}",clientId);
            throw new SystemException(MessageCode.ERROR_COMMONS_UNKNOWN);
        }
        Boolean online = emqxClient.getOnlineStatus(config.getEmqx(), MqttMessageType.USER.getUserTopic(active,statusReq.getUserId()));
        if(!online){
            String key = RedisKeyEnum.mqtt_user_online.getKey(statusReq.getUserId());
            stringRedisTemplate.delete(key);
            log.info("user({}) offline",statusReq.getUserId());
            emqxClient.sendMessageTopic(config.getEmqx(), MqttMessageType.USER_OFFLINE.getTopic(active,clientId),statusReq.getUserId());
        }
        return new StatusRes(online,statusReq.getPushChannel(),statusReq.getUserId());
    }
}
